package com.xpc.rpc.serialization.jdk;

import com.xpc.rpc.annotation.SPIClass;
import com.xpc.rpc.common.serialization.Serialization;
import org.apache.commons.lang3.SerializationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * jdk序列化和反序列化
 */
@SPIClass
public class JdkSerialization implements Serialization {


    private static final Logger LOGGER = LoggerFactory.getLogger(JdkSerialization.class);

    /**
     * 序列化
     */
    @Override
    public <T> byte[] serialize(T obj) {
        LOGGER.info("这是里JDK序列化方式。。。。。。。。。。。。。。。");
        if(obj == null) {
            throw new SerializationException("serialize is null");
        }
        try{
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(os);
            out.writeObject(obj);
            return os.toByteArray();
        }catch (IOException e) {
            e.printStackTrace();
            return null;
            //throw new SerializationException(e.getMessage(),e);
        }
    }

    /**
     * 反序列化
     */
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        if(data == null) {
            throw new SerializationException("deserialize data null");
        }
        try{
            ByteArrayInputStream is = new ByteArrayInputStream(data);
            ObjectInputStream in = new ObjectInputStream(is);
            return (T)in.readObject();
        }catch (Exception e) {
            throw new SerializationException(e.getMessage(),e);
        }
    }
}


